package org.xyl.context;

import java.util.*;
import org.xyl.context.KnowledgeContext.*;

/**
 * 知识上下文提供器 - 负责从知识库检索相关知识
 */
public class KnowledgeContextProvider {
    
    /**
     * 获取知识上下文
     * 这里模拟RAG知识库检索，实际实现需要连接真实的知识库系统
     */
    public KnowledgeContext getKnowledgeContext(String userQuery, 
                                              Map<String, List<String>> entities, 
                                              UserIntent intent) {
        KnowledgeContext context = new KnowledgeContext();
        
        // 根据意图和实体构建检索查询
        String searchQuery = buildSearchQuery(userQuery, entities, intent);
        
        // 模拟检索相关知识
        List<KnowledgeItem> results = searchKnowledgeBase(searchQuery, intent);
        
        // 添加检索结果到上下文
        for (KnowledgeItem item : results) {
            context.addKnowledgeItem(item);
        }
        
        return context;
    }
    
    // 构建检索查询
    private String buildSearchQuery(String userQuery, Map<String, List<String>> entities, UserIntent intent) {
        StringBuilder queryBuilder = new StringBuilder(userQuery);
        
        // 添加实体信息到查询
        if (entities.containsKey(EntityRecognizer.ENTITY_DEVICE_MODEL)) {
            for (String model : entities.get(EntityRecognizer.ENTITY_DEVICE_MODEL)) {
                queryBuilder.append(" ").append(model);
            }
        }
        
        // 根据意图添加关键词
        if (intent == UserIntent.DIAGNOSTIC) {
            queryBuilder.append(" 故障 诊断 排查");
        } else if (intent == UserIntent.SERVICE) {
            queryBuilder.append(" 规格 参数 使用说明");
        }
        
        return queryBuilder.toString();
    }
    
    // 模拟知识库检索
    private List<KnowledgeItem> searchKnowledgeBase(String query, UserIntent intent) {
        List<KnowledgeItem> results = new ArrayList<>();
        
        // 根据查询内容和意图返回模拟的知识库条目
        if (query.contains("ESL-202") && query.contains("低温")) {
            results.add(new KnowledgeItem(
                "ESL-202规格书", 
                "《ESL-202规格书》", 
                "工作温度：-20°C 至 70°C", 
                0.95
            ));
            
            results.add(new KnowledgeItem(
                "安装注意事项", 
                "《安装注意事项》", 
                "在低于-10°C时，电池性能会下降，建议减少刷新频率", 
                0.85
            ));
        } else if (query.contains("电量不足") || query.contains("电池电压")) {
            results.add(new KnowledgeItem(
                "故障代码手册", 
                "《故障代码手册》", 
                "电量不足警告时电压通常低于3.0V", 
                0.90
            ));
        } else if (query.contains("信号弱")) {
            results.add(new KnowledgeItem(
                "信号弱问题排查", 
                "知识库文章《信号弱问题排查》", 
                "建议检查设备安装位置", 
                0.88
            ));
        }
        
        return results;
    }
}